import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../dd_models/dd_hive_comment_model.dart';
import '../dd_models/dd_hive_my_style_model.dart';
import '../dd_models/dd_hive_video_model.dart';
import '../dd_models/dd_hive_works_model.dart';


class HiveService {

  static final HiveService _instance = HiveService._();

  HiveService._() {
    _registerAdapters();
  }

  factory HiveService() {
    return _instance;
  }

  static Future init() async {
    await Hive.initFlutter();
  }

  void _registerAdapters() {
    Hive.registerAdapter(HiveWorksModelAdapter());
    Hive.registerAdapter(HiveCommentModelAdapter());
    Hive.registerAdapter(HiveVideoModelAdapter());
    Hive.registerAdapter(HiveMyStyleModelAdapter());
  }

  Future<Box<T>> box<T>() async {
    var boxName = _getBoxName(T);

    if (!Hive.isBoxOpen(boxName)) {
      await Hive.openBox<T>(boxName);
    }
    return Hive.box<T>(_getBoxName(T));
  }

  String _getBoxName(Type type) {
    return type.toString();
  }

  /// Clears all the data stored in all boxes.
  Future<void> clearBoxes() async {
    Box<HiveWorksModel> box0 = await _instance.box<HiveWorksModel>();
    await box0.clear();
    Box<HiveMyStyleModel> box1 = await _instance.box<HiveMyStyleModel>();
    await box1.clear();
  }

  /// Close the boxes so they may not be accessible anymore unless reopened.
  Future<void> closeBoxes() async {
    await Hive.close();
  }


}